<template>
    <a-alert class="error mb16" v-if="errors.length" type="error" showIcon :message="`保存经费预算时发生错误：`">
        <template #description>
            <ul>
                <li v-for="(v, k) in errors" :key="k">{{ v }}</li>
            </ul>
        </template>
    </a-alert>
    <a-alert class="mb16" v-else type="info" showIcon message="填写提示">
        <template #description>
            <ol>
                <li>预计经费总额必须<b>等于</b>学校批准经费，各开支科目金额默认为0元。</li>
                <li>当学校批准经费栏目显示<b>“待定”</b>，请先填写预计经费分配情况。待学校给定批准经费后，再进行修改。</li>
                <li>主要用途栏目文本长度最长为<b>150字</b>。</li>
                <li>预算使用时间必须晚于项目申请时间，早于项目结束时间。</li>
            </ol>
        </template>
    </a-alert>
    <budget-editor class="mb16" ref="budgetRef" />
    <a-flex justify="space-between">
        <a-space>
            <a-button :disabled="overBudget" type="primary" @click="save" :loading><SaveOutlined />保存预算数据</a-button>
            <a-button @click="reset" :loading ><ReloadOutlined />还原所有修改</a-button>
        </a-space>
        <a-button :disabled="overBudget" type="primary" :loading>
            保存并前往下一页
            <ArrowRightOutlined />
        </a-button>
    </a-flex>
</template>

<script setup>
import BudgetEditor from '@proj/components/budget-editor.vue'
import { ref, inject, onMounted, watch } from 'vue'
import app from "@/app.ts";
import { axios } from '@/axios';

const budgetRef = ref();
const errors = ref([]);
const data = inject("data");
const loading = ref(false);
const overBudget = ref();

onMounted(() => {
    overBudget.value = budgetRef.value.overBudget;
    watch(() => budgetRef.value.overBudget, (v) => {
        overBudget.value = v;
    });
});



function reset () {
    budgetRef.value.reset();
}
async function save () {
    const bdgt = budgetRef.value;
    let flag = await bdgt.validate();
    errors.value=[...bdgt.errorStrings];
    if(!flag){
        return;
    }
    let handler = app.modals.loading("正在提交数据");
    loading.value = true;
    let msg = await axios.post("/api/proj/common/SaveBudget",{
        id: data.basicInfo.ID,
        budgets: bdgt.budgets
    });
    app.modals.showResponse(msg);

    if(msg.success){
        data.setBudgets(msg.budgets);
    }else{
        errors.value = [msg.msg];
    }
    loading.value=false;
    handler();
}

</script>

<style lang="less" scoped>
ol {
    list-style: decimal;
}
</style>